package com.shelpe.services.scheduler.item.keyword;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;

import com.shelpe.services.scheduler.dto.RptKeywordDto;
import com.shelpe.services.scheduler.mongorepository.UnrecoverableErrorRepository;
import com.shelpe.services.scheduler.po.Adgroups;
import com.shelpe.services.scheduler.po.SyncLog;
import com.shelpe.services.scheduler.syncclient.KeywordClient;
import com.shelpe.services.scheduler.util.Util;

public class RptKeywordProcessor implements ItemProcessor<Adgroups, SyncLog>{

	private static final Logger logger = LoggerFactory.getLogger(RptKeywordProcessor.class);
	
	@Autowired
	private KeywordClient keyClient;
	
	@Autowired
	private UnrecoverableErrorRepository errorRep;
	
	@Override
	public SyncLog process(Adgroups item) throws Exception {
		// TODO Auto-generated method stub
		
		long userId = item.getUserId();
		if(errorRep.countByUserId(userId) > 0){
			return null;
		}
		
		long adgroupId = item.getAdgroupId();
		long campaignId = item.getCampaignId();
		
		if(!item.getOnlineStatus().equalsIgnoreCase("online")){
			return null;
		}

		RptKeywordDto rptDto = keyClient.getSyncRptKeywordsRange(userId, campaignId, adgroupId);
			
		if(rptDto != null && rptDto.isNeedSync()){
			
			List<Map<String, String> > splitRange = Util.splitTaskRange(rptDto.getStartDate(), rptDto.getEndDate());
			//logger.info("userId: {}, adgroupId: {}, splitRange size {}", userId, adgroupId, splitRange.size());
			Calendar cal = Calendar.getInstance();	  
			int hour=cal.get(Calendar.HOUR_OF_DAY);//小时	
			String record = hour > 8 ? "no" : "yes";
			
			for(Map<String, String> map : splitRange){
				
				rptDto = keyClient.syncRptKeywordsByUserId(userId, campaignId, adgroupId, map.get("startDate"), map.get("endDate"), "scheduler", record);
			}
		}
		
		return Util.convert(rptDto);
	}
	
	
}
